package com.example.httpmessageconvert.httpmessageconvert.messageconfig;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author 奶茶
 * Created by on 2017/12/29.
 * 自定义消息转换类 能够处理request 和 response 参数
 */
@Configuration
public class JsonConvert extends AbstractHttpMessageConverter {

    /**
     * 自定义媒体类型
     */
    public JsonConvert(){
        super(new MediaType("application", "json", Charset.forName("UTF-8")));
    }

    /**
     * 设置支持的类型
     * ExamApp.class.isAssignableFrom(clazz) 设置只支持ExamApp类
     * 如果支持全部类型 直接返回 true
     * @param clazz
     * @return
     */
    @Override
    protected boolean supports(Class clazz) {
        return true;
    }

    /**
     * 获取request中body的数据 并作相应处理
     * @param clazz
     * @param inputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String string = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
        string += "999";
        return string;
    }

    /**
     * 获取response的数据 并作相应处理
     * @param examPlan
     * @param outputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    protected void writeInternal(Object examPlan, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(new UpperCase());
        String string = objectMapper.writeValueAsString(examPlan);
        outputMessage.getBody().write(string.getBytes("UTF-8"));
    }

}
